package com.xt.wikiperfumapi;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xt.wikiperfumapi.model.BrandInfo;
import com.xt.wikiperfumapi.model.IngredientInfo;
import com.xt.wikiperfumapi.model.PerfumeInfo;
import com.xt.wikiperfumapi.model.PerfumeIngredientRef;
import com.xt.wikiperfumapi.model.other.Ingredient;
import com.xt.wikiperfumapi.model.other.InitIngredients;
import com.xt.wikiperfumapi.service.impl.BrandInfoServiceImpl;
import com.xt.wikiperfumapi.service.impl.IngredientInfoServiceImpl;
import com.xt.wikiperfumapi.service.impl.PerfumeInfoServiceImpl;
import com.xt.wikiperfumapi.service.impl.PerfumeIngredientRefServiceImpl;
import com.xt.wikiperfumapi.util.RandomUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@SpringBootTest(classes = WikiPerformApiApplication.class)
@Slf4j
public class InitPerfumeData {

    @Resource
    PerfumeInfoServiceImpl perfumeInfoService;//香水信息

    @Resource
    PerfumeIngredientRefServiceImpl perfumeIngredientRefService;//香水和原料的关联表

    @Resource
    IngredientInfoServiceImpl ingredientInfoService;//原料表

    @Resource
    BrandInfoServiceImpl brandInfoService;

    @Resource
    RandomUtil randomUtil;


    @Test
    void initData() {
        try (FileReader reader = new FileReader("C:\\Users\\24862\\Desktop\\wiki\\data\\perfume-data.json")) {
            // 读取文件内容并构建 JSON 字符串
            StringBuilder jsonString = new StringBuilder();
            int ch;
            while ((ch = reader.read()) != -1) {
                jsonString.append((char) ch);
            }

            // 使用 fastjson 解析 JSON 字符串为 List<Ingredient>
            List<Ingredient> ingredients = JSON.parseArray(jsonString.toString(), Ingredient.class);

            long index = 1;
            // 输出 List<Ingredient> 内容
            for (Ingredient ing : ingredients) {
                PerfumeInfo perfumeInfo = new PerfumeInfo();
                perfumeInfo.setPerfumeId(index);
                perfumeInfo.setName(ing.getName());
                perfumeInfo.setBrandText(ing.getBrand());
                if (brandInfoService.count(new QueryWrapper<BrandInfo>().eq("name", ing.getBrand())) == 1) {
                    perfumeInfo.setBrandId(brandInfoService.getOne(new QueryWrapper<BrandInfo>().eq("name", ing.getBrand())).getBrandId());
                }//如果存在品牌将这个id传递
                perfumeInfo.setPrice(BigDecimal.valueOf(randomUtil.generateRandomNumber(100, 99999)));//随机价位
                perfumeInfo.setImg(ing.getImg());
                //这里是原料
                for (InitIngredients ingredient : ing.getIngredients()) {
                    if (ingredientInfoService.count(new QueryWrapper<IngredientInfo>().eq("name", ingredient.getName())) == 1) {
                        IngredientInfo infoServiceOne = ingredientInfoService.getOne(new QueryWrapper<IngredientInfo>().eq("name", ingredient.getName()));
                        infoServiceOne.setImg(ingredient.getImg());
                        ingredientInfoService.updateById(infoServiceOne);//如果存在那么就可以更新材料的图片
                    } else {
                        ingredientInfoService.remove(new QueryWrapper<IngredientInfo>().eq("name", ingredient.getName()));//重新删除再添加
                        IngredientInfo info = new IngredientInfo();
                        info.setName(ingredient.getName());
                        info.setImg(ingredient.getImg());
                        info.setFragranceNoteId(17L);//因为之前有的都加了，那么没有的，就是未知的
                        info.setInputTime(new Date());
                        ingredientInfoService.save(info);
                    }
                    //这里更新原料图片，如果没有那么就更新原料
                    IngredientInfo info = ingredientInfoService.getOne(new QueryWrapper<IngredientInfo>().eq("name", ingredient.getName()));
                    //这里直接取出来
                    PerfumeIngredientRef perfumeIngredientRef = new PerfumeIngredientRef();
                    perfumeIngredientRef.setPerfumeId(index);
                    perfumeIngredientRef.setIngredientId(info.getIngredientId());
                    perfumeIngredientRefService.save(perfumeIngredientRef);//这里更新原料与香水之间的关系
                }
                perfumeInfo.setFragranceNote(ing.getFamily());//香调
                perfumeInfo.setSmell(ing.getSecondFamily());//香型
                index++;//索引加一
                perfumeInfoService.save(perfumeInfo);
                log.info(JSON.toJSONString(perfumeInfo));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Test
    void updatePerfurmYear() {
        try (FileReader reader = new FileReader("C:\\Users\\24862\\Desktop\\wiki\\data\\perfume-data.json")) {
            // 读取文件内容并构建 JSON 字符串
            StringBuilder jsonString = new StringBuilder();
            int ch;
            while ((ch = reader.read()) != -1) {
                jsonString.append((char) ch);
            }

            // 使用 fastjson 解析 JSON 字符串为 List<Ingredient>
            List<Ingredient> ingredients = JSON.parseArray(jsonString.toString(), Ingredient.class);

            // 输出 List<Ingredient> 内容
            for (Ingredient ing : ingredients) {
                PerfumeInfo perfumeInfo = perfumeInfoService.getOne(new QueryWrapper<PerfumeInfo>().eq("name", ing.getName()).eq("img", ing.getImg()).eq("smell", ing.getSecondFamily()).eq("fragrance_note", ing.getFamily()));
                perfumeInfo.setYear(Integer.valueOf(ing.getYear()));//更新年份
                for (InitIngredients ingredient : ing.getIngredients()) {
                    String string = JSON.toJSONString(ingredient);
                    perfumeInfo.setIngredients(string);
                }
                perfumeInfoService.updateById(perfumeInfo);//更新
                log.info(JSON.toJSONString(perfumeInfo));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    void initSex() {
        try (FileReader reader = new FileReader("C:\\Users\\24862\\Desktop\\wiki\\data\\perfume-all-data.json")) {
            // 读取文件内容并构建 JSON 字符串
            StringBuilder jsonString = new StringBuilder();
            int ch;
            while ((ch = reader.read()) != -1) {
                jsonString.append((char) ch);
            }

            // 使用 fastjson 解析 JSON 字符串为 List<Ingredient>
            List<Ingredient> ingredients = JSON.parseArray(jsonString.toString(), Ingredient.class);

            // 输出 List<Ingredient> 内容
            for (Ingredient ing : ingredients) {
                PerfumeInfo perfumeInfo = perfumeInfoService.getOne(new QueryWrapper<PerfumeInfo>().eq("name", ing.getName()).eq("img", ing.getImg()).eq("smell", ing.getSecondFamily()).eq("fragrance_note", ing.getFamily()));
                perfumeInfo.setSex(ing.getSex_());
                perfumeInfoService.updateById(perfumeInfo);//更新
                log.info(JSON.toJSONString(perfumeInfo));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    void updatePerfurmIngredient() {
        for (PerfumeInfo perfumeInfo : perfumeInfoService.list()) {
            List<PerfumeIngredientRef> perfumeIngredientRefs = perfumeIngredientRefService.list(new QueryWrapper<PerfumeIngredientRef>().eq("perfume_id", perfumeInfo.getPerfumeId()));

            // 使用 StringBuilder 来拼接字符串
            StringBuilder strBuilder = new StringBuilder();

            perfumeIngredientRefs.forEach(ref -> {
                IngredientInfo ingredient = ingredientInfoService.getById(ref.getIngredientId());
                String name = ingredient.getName();

                // 如果不是第一个元素，则加逗号
                if (strBuilder.length() > 0) {
                    strBuilder.append(",");
                }
                strBuilder.append(name);
            });

            // 将拼接好的字符串设置到 perfumeInfo 的 ingredients 字段
            perfumeInfo.setIngredients(strBuilder.toString());
            perfumeInfoService.updateById(perfumeInfo);
            System.out.println(perfumeInfo.getIngredients());  // 输出拼接后的结果
        }


    }

    @Test
    void reflush() {
        List<PerfumeInfo> list = perfumeInfoService.list();
        for (int i = 0; i < list.size(); i++) {
            PerfumeInfo perfumeInfo = list.get(i);
            perfumeInfo.setPerfumeId((long)i+1);
            perfumeInfoService.updateById(list.get(i));
        }

    }

    void reflushIngredient(){
        List<IngredientInfo> ingredientInfos = ingredientInfoService.list();

    }

}
